package com.starmark.sys.org.atomic.web;


import com.starmark.core.framework.base.AbstractController;
import com.starmark.core.framework.response.Response;
import com.starmark.core.framework.response.SuccessResponseData;
import com.starmark.core.framework.util.BeanMapper;
import com.starmark.sys.org.api.dto.OrgElementDto;
import com.starmark.sys.org.atomic.entity.SysOrgDept;
import com.starmark.sys.org.atomic.service.ISysOrgDeptService;
import com.starmark.sys.org.atomic.vo.SysOrgDeptVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * 部门管理控制类
 */
@RestController
@Api(value = "部门管理", description = "部门管理")
@RequestMapping(value = "/sys/org/dept")
public class SysOrgDeptController extends AbstractController {


    @Autowired
    private ISysOrgDeptService sysOrgDeptService;

    @ApiOperation(value = "查询部门树")
    @PostMapping(value = "/deptTree")
    public List<OrgElementDto> deptTree(@RequestParam("parentId") String parentId) {

        return sysOrgDeptService.getOrgTreeById(parentId);
    }


    @ApiOperation(value = "查询部门")
    @PostMapping(value = "/query")
    public Object query(@RequestBody Map<String, Object> param) {

        return BeanMapper.mapPage(sysOrgDeptService.query(param), SysOrgDeptVo.class);
    }

    @ApiOperation(value = "新增部门")
    @PostMapping
    public SuccessResponseData add(@RequestBody SysOrgDeptVo sysOrgDeptVo) {


        return SuccessResponseData.newInstance( sysOrgDeptService.saveDept(sysOrgDeptVo));
    }

    @ApiOperation(value = "部门详情")
    @GetMapping(value = "/{id}")
    public SysOrgDeptVo get(@PathVariable("id") String id) {
        SysOrgDept sysOrgDept = sysOrgDeptService.getById(id);
        SysOrgDeptVo sysOrgDeptVo = BeanMapper.map(sysOrgDept, SysOrgDeptVo.class);
        // 设置部门名称
        Optional.ofNullable(sysOrgDeptVo.getParentId())
                .ifPresent(deptId -> sysOrgDeptVo.setParentName(sysOrgDeptService.getById(deptId).getName()));
        return sysOrgDeptVo;
    }

    @PutMapping
    @ApiOperation(value = "修改部门")
    public Response update(@RequestBody SysOrgDeptVo sysOrgDeptVo) {

        return SuccessResponseData.newInstance(sysOrgDeptService.updateDept(sysOrgDeptVo));
    }


    @DeleteMapping(value = "/{id}")
    @ApiOperation(value = "删除部门")
    public void delete(@PathVariable("id") String id) {
        sysOrgDeptService.removeById(id);
    }
}
